
package com.oahcfly.chgame.core.map;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.oahcfly.chgame.core.Chao;

/**
 * 
 * 绘制方块地图，平铺到设定的宽高内，核心代码参考TiledDrawable。
 * @author haocao
 *
 */
public class CHTiledActor extends Actor {

	private float mapW, mapH;
	private Texture texture;

	/**
	 * 
	 * @param pngPath 方块图片
	 * @param mapW 绘制宽
	 * @param mapH 绘制高
	 */
	public CHTiledActor (String pngPath, float mapW, float mapH) {
		texture = Chao.game.getTexture(pngPath);
		this.mapW = mapW;
		this.mapH = mapH;
		setSize(mapW, mapH);
	}

	@Override
	public void draw (Batch batch, float parentAlpha) {
		batch.setColor(getColor());

		float regionWidth = texture.getWidth(), regionHeight = texture.getHeight();
		int fullX = (int)(mapW / regionWidth), fullY = (int)(mapH / regionHeight);
		float remainingX = mapW - regionWidth * fullX, remainingY = mapH - regionHeight * fullY;
		float startX = getX(), startY = getY();

		float tmpx = getX();
		float tmpy = getY();
		for (int i = 0; i < fullX; i++) {
			tmpy = startY;
			for (int ii = 0; ii < fullY; ii++) {
				batch.draw(texture, tmpx, tmpy, regionWidth, regionHeight);
				tmpy += regionHeight;
			}
			tmpx += regionWidth;
		}

		float u = 0;
		float v2 = 1;
		if (remainingX > 0) {
			// Right edge.
			float u2 = u + remainingX / texture.getWidth();
			float v = 0;
			tmpy = startY;
			for (int ii = 0; ii < fullY; ii++) {
				batch.draw(texture, tmpx, tmpy, remainingX, regionHeight, u, v2, u2, v);
				tmpy += regionHeight;
			}
			// Upper right corner.
			if (remainingY > 0) {
				v = v2 - remainingY / texture.getHeight();
				batch.draw(texture, tmpx, tmpy, remainingX, remainingY, u, v2, u2, v);
			}
		}
		if (remainingY > 0) {
			// Top edge.
			float u2 = 1;
			float v = v2 - remainingY / texture.getHeight();
			tmpx = startX;
			for (int i = 0; i < fullX; i++) {
				batch.draw(texture, tmpx, tmpy, regionWidth, remainingY, u, v2, u2, v);
				tmpx += regionWidth;
			}
		}

	}

}
